package com.chinaunicom.config;

import cn.hutool.core.io.FileUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.nio.charset.Charset;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/3/8 16:13
 * Description: token解析配置,获取用户信息
 */

@Configuration
public class ResourceConfig extends ResourceServerConfigurerAdapter {

    /**
     * 转换jwt
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter getJwtAccessTokenConverter() {
        try {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            // 非对称解密
            ClassPathResource resource = new ClassPathResource("publickey.txt");

            // 读取加密文件为字符串
            String publicKey = FileUtil.readString(resource.getFile(), Charset.defaultCharset());

            // 设置签名
            converter.setVerifierKey(publicKey);
            return converter;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    @Bean
    public TokenStore getTokenStore() {
        return new JwtTokenStore(getJwtAccessTokenConverter());
    }


    /**
     * 让资源服务器从 tokenStore中获取token
     *
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(getTokenStore());
    }
}
